package org.apple.averager;

import java.util.Properties;
import java.util.Vector;

import org.apple.data.SensorReading;
import org.apple.databanker.*;
import org.apple.data.*;
import org.apple.util.Configure;

public class AirTemperatureAverager implements Averager {
	
	private int highWeight;
	private int lowWeight;
	private DataBanker databanker; 
	
	public AirTemperatureAverager() {
		Configure configure = Configure.instance();
		
		this.highWeight = Integer.parseInt(configure
				.getProperty("airTemperatureHighWeight"));
		System.out.println("Configure: [ContAirTemperatureAveragerroller -> highWeight]\t"
				+ highWeight);
		
		this.lowWeight = Integer.parseInt(configure
				.getProperty("airTemperatureLowWeight"));
		System.out.println("Configure: [ContAirTemperatureAveragerroller -> lowWeight]\t"
				+ lowWeight);
	}

	public SensorReading average() {

		double weight = 0;
		double value = 0;
		double airtemperature = 0;
		Properties prop = Configure.instance();
		SensorReading sensorreading = new SensorReading(
				SensorReading.AIRTEMPRATURE, 0, 0);
		Vector<SensorReading> SensorReadings = new Vector<SensorReading>();
		try {
			databanker = (DataBanker)Class.forName(prop.getProperty("dataBankerType")).newInstance();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		databanker.read(SensorReadings, SensorReading.AIRTEMPRATURE);
		SensorReading sr = new SensorReading(0, 0, 0);
		if (SensorReadings.size() == 0) {
			airtemperature = SensorReading.NOAIRTEMPRATURE;
			System.out
					.print("The data banker has no readings, please try again");
		} else {
			for (int i = 0; i < SensorReadings.size(); i++) {
				sr = (SensorReading) SensorReadings.elementAt(i);
				if (sr.getResolutionType() == SensorResolution.HighRes) {
					value = sr.getValue() * highWeight + value;
					weight = weight + highWeight;
				} else {
					value = sr.getValue() * lowWeight + value;
					weight = weight + lowWeight;
				}

			}
			airtemperature = value /weight;
			
		}

		sensorreading.setValue(airtemperature);
		return sensorreading;
	}

}
